package com.sjs.flow.utils;

import com.sjs.flow.http.exception.PlatformException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Create by hefy
 * @Date 2021/11/29 9:26
 */
@Component
public class CommonContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static ConfigurableApplicationContext configurableApplicationContext;

    private static DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CommonContextUtil.applicationContext = applicationContext;

        configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;

        defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();

    }


    public static <T> T getBean(Class<T> c) {
        try {
            T cc = applicationContext.getBean(c);
            return cc;
        } catch (Exception e) {
            throw new PlatformException(e.getMessage(), 10000001);
        }
    }

    public static <T> T getBeanByName(String name) {
        try {
            T cc = (T) applicationContext.getBean(name);
            return cc;
        } catch (Exception e) {
            throw new PlatformException(e.getMessage(), 10000001);
        }
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static ApplicationContext getApplicationContext() {

        return applicationContext;

    }

    public static <T> List<T> getBeanListOfType(Class<T> clazz) {
        List<T> result = new ArrayList<>();
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        if (null != map) {
            result.addAll(map.values());
        }
        return result;
    }

    public static void registorBean(String beanName, Class<?> clazz) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
    }
}
